import crypto from 'crypto'
import Datastore from 'nedb-promises';
import { app,ipcMain}  from 'electron';
import spotAPI  from './hb-spot-api';
import path from 'path';
import axios from 'axios';
import moment from 'moment';
const math = require('mathjs');


var basePath = app.getPath('userData');
basePath = path.join(basePath,'db')





var db = {
    key : new Datastore({
        autoload:true,
        timestampData:true,
        filename:path.join(basePath,'huobi/key.db')
    }),
    task : new Datastore({
        autoload:true,
        timestampData:true,
        filename:path.join(basePath,'huobi/task.db')
    }),
    symbol : new Datastore({
        autoload:true,
        timestampData:true,
        filename:path.join(basePath,'huobi/symbol.db')
    }),
    trade: new Datastore({
        autoload:true,
        timestampData:true,
        filename:path.join(basePath,'huobi/trade.db')
    }), 
    report: new Datastore({
        autoload:true,
        timestampData:true,
        filename:path.join(basePath,'huobi/report.db')
    }), 
    reportFlag: new Datastore({
        autoload:true,
        timestampData:false,
        filename:path.join(basePath,'huobi/reportFlag.db')
    }), 
    auth: new Datastore({
        autoload:true,
        timestampData:true,
        filename:path.join(basePath,'huobi/auth.db')
    }), 
}



class Response{
        constructor(success,data){
            this.success = success;
            this.data = data;
        }
}






ipcMain.on('initSymbols',async (event,data)=>{
    let result = await spotAPI.getSymbols();
    if(result.success){
        await db.symbol.remove({}, { multi: true });
        db.symbol.insert(result.data)
        event.reply('initSymbols-res',new Response(true,result.data));
    }
})





ipcMain.on('saveAuth',async (event,data)=>{
    await db.auth.remove({}, { multi: true });
    let count = await db.auth.insert(data);
    event.reply('saveAuth-res',new Response(true,count));
})

ipcMain.on('getAuth',async (event,data)=>{
    let doc = await db.auth.findOne();
    event.reply('getAuth-res',new Response(true,doc));
})


ipcMain.on('checkAuth',async (event,data)=>{
    let authInfo = {};
    let doc = await db.auth.findOne();
     if(doc && doc.email && doc.authCode){
        try{
            let buffer = Buffer.from(doc.authCode, 'base64')
            let decrypted = crypto.publicDecrypt(global.CONFIG.publicKey,buffer);
            let strs = decrypted.toString("utf8").split('|');
            if(strs.length == 2 && strs[0] == doc.email){
                //检查时间
                let res = await axios.get('http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp')
                if(res.status != 200){
                    authInfo.valid = false;
                    authInfo.content = '授权时网络异常，请重试';
                    event.reply('checkAuth-res', new Response(true,authInfo))
                    return;
                }
                let curDate = moment(res.data.data.t - 0).format('YYYY-MM-DD');
                if(curDate > strs[1]){
                    authInfo.valid = false;
                    authInfo.content = '授权码过期，授权截止日期：' + strs[1] + '，请重新购买。';
                    event.reply('checkAuth-res', new Response(true,authInfo))
                }else{
                    authInfo.valid = true;
                    authInfo.content = '授权成功，授权截止日期：' + strs[1];
                    event.reply('checkAuth-res', new Response(true,authInfo))
                }
            }else{
                authInfo.valid = false;
                authInfo.content = '授权失败,请购买授权码。';
                event.reply('checkAuth-res', new Response(true,authInfo))
            }
        }catch(err){
            authInfo.valid = false;
            authInfo.content = '授权失败,请购买授权码。';
            event.reply('checkAuth-res', new Response(true,authInfo))
        }
       
     }else{
        authInfo.valid = false;
        authInfo.content = '未授权，请购买授权码。';
        event.reply('checkAuth-res', new Response(true,authInfo))
     }
})

ipcMain.on('saveTask',async (event,data)=>{
    if(data._id){
        // 设置upsert
        let count = await db.task.update({ _id: data._id }, data,{upsert:true});
        event.reply('saveTask-res', new Response(true,count))
    }else{
        let d = await db.task.insert(data);
        event.reply('saveTask-res', new Response(true,d))
    }
    
})

ipcMain.on('updateTaskState',async (event,data)=>{
 let count = await db.task.update({ _id: data._id }, { $set: { state: data.state } });
 event.reply('updateTaskState-res', new Response(true,count))
})


ipcMain.on('closeTask',async (event,data)=>{
    let count = await db.task.update({ _id: data._id }, { $set: { state: 0 } });
    event.reply('closeTask-res', new Response(true,count))
   })

ipcMain.on('removeTaskById',async (event,_id)=>{
    let count = await db.task.update({ _id: _id }, { $set: { state: -1 } });
    event.reply('removeTaskById-res', new Response(true,count))
   
})

ipcMain.on('updateTaskSort',(event,list)=>{
    for(var i in list){
        let data = list[i];
        db.task.update({ _id: data._id }, { $set: { sort: data.sort } });
    }
   })




ipcMain.on('getTaskById',async (event,id)=>{
    let doc = await db.task.findOne({ _id: id });
    event.reply('getTaskById-res', new Response(true,doc))
})

ipcMain.on('listTask',async (event,arg)=>{
    let list = await db.task.find({state:{ $ne: -1}}).sort({ sort: 1 });
    event.reply('listTask-res', list)
})


ipcMain.on('listSymbol',async (event,arg)=>{
    let list = global.CONFIG.huobi.symbols;
    let arr = [];
    for(let i in list){
        if(list[i]['quote-currency'] == 'usdt'){
            arr.push(list[i])
        }
    }
    
    let sorted = arr.sort(function(a,b){
        let tempa = a['quote-currency'] + a['base-currency'];
        let tempb = b['quote-currency'] + b['base-currency'];
          return tempa > tempb ? 1 : -1;
        
    })
    event.reply('listSymbol-res', sorted)
})


ipcMain.on('saveKey',async (event,data)=>{
    await db.key.remove({}, { multi: true });
    let count = await db.key.insert(data);
    global.CONFIG.huobi.accessKey = data.accessKey;
    global.CONFIG.huobi.secretKey = data.secretKey;
    global.CONFIG.huobi.httpBaseUrl = 'https://' + data.host;
    global.CONFIG.huobi.wsUrl = 'wss://'+data.host+'/ws';
    event.reply('saveKey-res', new Response(true,count))
})


ipcMain.on('getKey',async (event,data)=>{
    let doc = await db.key.findOne();
    event.reply('getKey-res', new Response(true,doc))
})

ipcMain.on('testKey',async (event,data)=>{
    let result = await spotAPI.testKey(data);
    event.reply('testKey-res', result)
})



ipcMain.on('listTrade',async (event,data)=>{
    let list = await db.trade.find({status:1,quoteCurrency:data.quoteCurrency});
    event.reply('listTrade-res', list)
})

ipcMain.on('listAllTrade',async (event,data)=>{
    let list = await db.trade.find({status:1});
    event.reply('listAllTrade-res', list)
})

ipcMain.on('listTradeByTaskId',async (event,data)=>{
    let list = await db.trade.find({status:1,taskId:data.taskId,loopCount:data.loopCount});
    event.reply('listTradeByTaskId-res', list)
})



ipcMain.on('existsTradeForTaskId',async (event,taskId)=>{
    let doc = await db.trade.findOne({taskId:taskId});
    if(doc){
        event.reply('existsTradeForTaskId-res', true)
    }else{
        event.reply('existsTradeForTaskId-res', false)
    }

    
})




ipcMain.on('sellAll',async (event,id)=>{
    let doc = await db.task.findOne({ _id: id });
    if(doc.state == 1){
        
        return;
    }
})


ipcMain.on('updateQuitState',async (event,data)=>{
    db.task.update({ _id: data._id }, { $set: { quit: parseInt(data.state) } });
})

ipcMain.on('updateTradeState',async (event,data)=>{
    db.task.update({ _id: data._id }, { $set: { stopTrade: parseInt(data.state) } });
    event.reply('updateTradeState-res', true)
})

ipcMain.on('reportFlag',async (event,data)=>{
    let doc = await db.reportFlag.findOne();
    event.reply('reportFlag-res', new Response(true,doc));
})

ipcMain.on('updateReportFlag',async (event,data)=>{
    await db.reportFlag.remove({}, { multi: true });
    let count = await db.reportFlag.insert({flag:1});
    event.reply('updateReportFlag-res', new Response(true,count));
})


ipcMain.on('insertReport',async (event,data)=>{
    let count = await db.report.insert(data);
    event.reply('insertReport-res', new Response(true,count));
})

ipcMain.on('updateReport',async (event,data)=>{
    await db.report.remove({}, { multi: true });
    let count = await db.report.insert(data);
    event.reply('updateReport-res', new Response(true,count));
})

ipcMain.on('deleteReportById',async (event,data)=>{
    let count = await db.report.remove({_id:data.id});
    event.reply('deleteReportById-res', new Response(true,count));
})
ipcMain.on('listReport',async (event,data)=>{
    let page = data.page;
    let pageSize = data.pageSize;
    let offset = (page - 1) * pageSize;
    let datetime = 0;
    if(data.days > 0){
        datetime = moment(moment().format('YYYY-MM-DD'),'YYYY-MM-DD').unix() - (data.days * 24*60*60);
    }
    let list = await db.report.find({quoteCurrency:data.quoteCurrency,datetime:{$gt: datetime}}).sort({ datetime: -1 }).skip(offset).limit(pageSize);
    let total = await db.report.count({quoteCurrency:data.quoteCurrency,datetime:{$gt: datetime}});
    let allList = await db.report.find({quoteCurrency:data.quoteCurrency,datetime:{$gt: datetime}});
    let profitSum = math.chain(0);
    for(let i in allList){
        profitSum = profitSum.add(allList[i].profit);
    }
    
    let pageData = {list:list,total:total,profitSum:profitSum.toString()};
    event.reply('listReport-res', new Response(true,pageData));
})



//在webpack打包的时候，可以在js文件中混用require和export。但是不能混用import 以及module.exports
// module.exports = {a:2};
export default db